<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12" :hidden="true">
            <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle" >
              <a-input :max-length="255" :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入流程名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectNo">
              <a-input :disabled="isDisableProjectNo" v-model="model.projectNo" placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm"
                style="width: 100%"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
              <!--              <select-user-by-dep-->
              <!--                :disabled=formDisabled-->
              <!--                v-model="model.proposer" disabled/>-->
              <select-user-by-dep :multi="false" v-model="model.proposer" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
              <j-select-depart v-model="model.proposerDeptId" disabled/>
            </a-form-model-item>
          </a-col>
          <a-divider>基本信息</a-divider>
          <a-col :span="12">
            <a-form-model-item label="选择已立项项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <select-project-input
                :data-isolation="'create_by'"
                :data-type="'username'"
                :proDisabled="proDisabled"
                :projectStatus="'2'"
                :disabled="formDisabled"
                :changeStatus="'unchanged'"
                v-model="model.projectId"
                @back="projectChange"/>
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="12">-->
          <!--            <a-form-model-item label="是否分配" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isBidding">-->
          <!--              <j-dict-select-tag :disabled=formDisabled type="radio" value="0" v-model="model.isBidding"-->
          <!--                                 dictCode="YES_OR_NO" placeholder="请输入是否分配"></j-dict-select-tag>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!-- <a-col :span="12">
            <a-form-model-item label="台账管理员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="accountAdmin">
              <select-user-by-dep
                  :disabled=formDisabled
                  v-model="model.accountAdmin"/>
            </a-form-model-item>
          </a-col> -->

          <!-- 迭代版升级1新增立项变更可修改项目名称 -->
          <a-col :span="12">
            <a-form-model-item label="是否变更项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isChangeName">
              <j-dict-select-tag
                :disabled="formDisabled"
                type="radio"
                v-model="model.isChangeName"
                dictCode="YES_OR_NO"
                @input="inputChangeName"
                placeholder="请选择是否变更项目名称"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="model.isChangeName == 1">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectName">
              <a-input @change="changeTitle" :disabled="formDisabled" v-model="model.projectName" placeholder="请输入项目名称"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamName">
              <select-team-input
                :disabled="formDisabled || isHasContract"
                v-model="model.teamName"
                :tdlx="1"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="undertaker">
              <!--              <select-user-by-dep-->
              <!--                :disabled=formDisabled-->
              <!--                v-model="model.undertaker"/>-->
              <select-user-by-dep :disabled="formDisabled || isHasContract" :multi="false" v-model="model.undertaker" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="立项日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectEstablishDate">
              <j-date
                :disabled="formDisabled || isHasContract"
                placeholder="请选择立项日期"
                v-model="model.projectEstablishDate"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signUnit">
              <!--              <j-select-company :disabled=formDisabled placeholder="请选择签订单位" v-model="model.signUnit"/>-->
              <select-Company-input :disabled="formDisabled || isHasContract" placeholder="请选择签订单位" v-model="model.signUnit"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag
                :disabled="formDisabled || isHasContract"
                type="list"
                v-model="model.year"
                dictCode="yjgsnd"
                placeholder="请选择归属年度"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="是否环评项目"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="isEnvironmentalAssessmentProject">
              <j-dict-select-tag
                :disabled="formDisabled || isHasContract"
                type="radio"
                v-model="model.isEnvironmentalAssessmentProject"
                dictCode="YES_OR_NO"
                placeholder="请选择是否环评项目"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ownerUnit">
              <select-customer-input
                :disabled="formDisabled || isHasContract"
                v-model="model.ownerUnit"
                commercialType="1"
                @change="ownerUnitChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contacts">
              <j-dict-select-tag
                :disabled="formDisabled || isHasContract"
                v-if="model.ownerUnit"
                type="list"
                v-model="model.contacts"
                :dictCode="this.customer_contacts"
                placeholder="请选择联系人"
                @input="contactsChange"
                :triggerChange="false"/>
              <j-dict-select-tag
                :disabled="true"
                type="list"
                v-else
                v-model="model.contacts"
                :dictCode="this.customer_contacts"
                placeholder="请选择联系人"
                @input="contactsChange"
                :triggerChange="false"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contactTel">
              <a-input :disabled="formDisabled || isHasContract" v-model="model.contactTel" placeholder="请输入联系方式"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="项目所在地址"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="height:65px"
              prop="projectAddress">
              <a-form-model-item :style="{display:'inline-block',width:'48%'}" prop="projectAddress">
                <AddressChoice :disabled="formDisabled || isHasContract" v-model="model.areaCode" placeholder="请选择省市区"></AddressChoice>
              </a-form-model-item>
              <a-form-model-item
                :style="{'margin-top':'0px','margin-left':'5px',display:'inline-block',width:'50%'}"
                prop="projectAddress">
                <a-input :disabled="formDisabled || isHasContract" v-model="model.projectAddress" placeholder="请输入项目详细地址"></a-input>
              </a-form-model-item>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目来源" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectSource">
              <j-dict-select-tag
                :disabled="formDisabled || isHasContract"
                type="list"
                v-model="model.projectSource"
                dictCode="xmly_type"
                placeholder="请选择项目来源"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="预计合同额（元）"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="estimatedContractAmount">
              <a-input-number
                :disabled="formDisabled || isHasContract"
                :max="99999999"
                :min="0"
                :precision="2"
                v-model="model.estimatedContractAmount"
                placeholder="请输入预计合同额"
                style="width: 100%"
                @change="convertMoney"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="预计合同额大写"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="estimatedContractcapitalChineseAmount">
              <a-input
                disabled
                v-model="model.estimatedContractcapitalChineseAmount"
                placeholder="请输入预计合同额大写"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item
              label="分配方式"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="distributionMethod">

              <j-dict-select-tag
                :disabled="formDisabled"
                type="list"
                v-model="model.distributionMethod"
                dictCode="distribution_method"
                placeholder="请选择分配方式"
                @change="getForMoney()"/>

            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="立项事由及说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="establishReason">
              <a-textarea :disabled="formDisabled || isHasContract" :max-length="500" v-model="model.establishReason" rows="4" placeholder="请输入立项事由及说明"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="相关附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
              <j-upload :disabled="formDisabled || isHasContract" if="!formDisabled" v-model="model.attachment"></j-upload>
            </a-form-model-item>
          </a-col>
          <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->

          <!-- <div> -->
          <!-- <div class="table-operator" style="margin-bottom: 6px;margin-top: 6px" >

            </div> -->
          <a-col :span="24" style="margin-bottom: 24px">
            <a-button @click="addOrEdit('')" style="margin-bottom: 10px;" v-if="!formDisabled" type="primary">新增</a-button>
            <a-table
              ref="table"
              size="middle"
              rowKey="id"
              :loading="loading"
              :columns="columns"
              :pagination="false"
              bordered
              :scroll="{x:'100%'}"
              :components="draggableComponent"
              :data-source="dataSource">
              <span slot="action" slot-scope="text, record">
                <template v-if="!formDisabled">
                  <a-button
                    class="ruleButton"
                    :ghost="true"
                    type="primary"
                    icon="edit"
                    @click="addOrEdit(record)"/>
                  <a-divider type="vertical" v-if="record.version === null || record.version === undefined || record.version === 0"/>
                  <a-popconfirm
                    v-if="record.version === null || record.version === undefined || record.version === 0"
                    title="确定删除吗?"
                    @confirm="() => handleDelete(record.id)">
                    <a-button
                      class="ruleButton"
                      :ghost="true"
                      type="primary"
                      icon="delete"
                    />
                  </a-popconfirm>
                </template>
              </span>
            </a-table>
          </a-col>
          <!-- </div> -->

          <!-- <template v-if="!detailFlag">
              <a-col :span="24" style="margin-bottom: 24px">
                  <j-vxe-table
                    ref="vTable"
                    row-number
                    keep-source
                    height="auto"
                    :loading="loading"
                    :dataSource="dataSource"
                    :columns="columns"
                    @valueChange="handleValueChange"
                  >
                </j-vxe-table>
              </a-col>
            </template>
            <template v-else>
              <a-col :span="24" style="margin-bottom: 24px">
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  :loading="loading"
                  :columns="detailColumns"
                  :pagination="false"
                  :data-source="dataSource">
                </a-table>
              </a-col>
            </template> -->

        </a-row>
        <div style="height: 30px"></div>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <erp-my-omc-project-task-modal ref="categoryList" @ok="modalFormOk" :distributionMethod="model.distributionMethod"/>
    </j-form-container>

    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpOmcProjectChangeFormPrint v-if="formBpm" class="print_style" id="projectApplyChangeContent" :formData="model" :formDataHistory="formData"/>
    <!-- <erp-omc-project-task-list ref="categoryList"></erp-omc-project-task-list> -->
  </a-spin>
</template>

<script>

import { getAction, httpAction, postAction } from '@/api/manage'
import SelectTeamInput from '@views/scy/components/SelectTeamInput';
import SelectCustomerInput from '@views/scy/components/SelectCustomerInput';
import { convertCurrency } from '@/utils/MoneyConvert';
import ErpMyOmcProjectTaskModal from '@views/erp/omc/project/modules/reference/ErpMyOmcProjectTaskModal';
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
// import ErpOmcProjectTaskList from '@views/erp/omc/project/ErpOmcProjectTaskList';
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectProjectInput from '@/views/scy/components/SelectProjectInput';
import AddressChoice from '@/components/AddressChoice/AddressChoice';
// import { JVXETypes } from '@/components/jeecg/JVxeTable';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep';
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import ErpOmcProjectChangeFormPrint from './ErpOmcProjectChangeFormPrint' // 立项变更打印
import Print from '@/utils/print/printarea.js'
import { DragResizable } from '@/mixins/DragResizable'

let queryContractByProjectId = '/api/erp/omc/contractmanager/erpOmcContractManagerFinal/queryContractByProjectId' // 根据项目id查询合同档案里是否存在收款合同
let valdateProductTeamLeader = '/api/erp/omc/project/erpOmcProjectApply/valdateEachProductTeamLeader' // 校验团队生产负责人岗位是否存在
// 校验项目名称是否唯一
var projectId = ''
let checkProjectName = (rule, value, callback) => {
  if (!value) {
    return
  }
  let params = {
    projectName: value,
    projectId: projectId
  }
  getAction('/api/erp/omc/project/erpOmcProject/checkProjectDuplicate', params).then(res => {
    if (res.success) {
      callback();
    } else {
      callback(new Error(res.message));
    }
  }).catch(error => {
    callback(new Error(error.message));
  })
}
export default {
  name: 'ErpOmcProjectChangeForm',
  components: {
    AddressChoice,
    SelectTeamInput,
    SelectUserByDep,
    SelectCustomerInput,
    SelectProjectInput,
    ErpMyOmcProjectTaskModal,
    SelectCompanyInput,
    CommonFlowList,
    ErpOmcProjectChangeFormPrint
  },
  mixins: [DragResizable],
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      oldProjectName: '', // 旧项目名称
      isHasContract: false, // 是否有收款合同
      detailFlag: false,
      allowChange: false,
      isDisableProjectNo: false,
      model: {
        isEnvironmentalAssessmentProject: '0',
        isPrepareEstablish: '0',
        isBidding: '0'
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        projectAddress: [
          { required: true, message: '请输入项目所在地址!' }
        ],
        bpmBizTitle: [
          { required: true, message: '请输入流程名称!' }
        ],
        // task#2118 task#2118 是否环评改为必填项，默认为否
        isEnvironmentalAssessmentProject: [
          { required: true, message: '请输入是否环评!' }
        ],
        projectId: [
          { required: true, message: '请输入已立项项目!' }
        ],
        projectNo: [
          { required: true, message: '请输入已立项项目编号!' }
          // { validator: (rule, value, callback) => validateDuplicateValue('erp_omc_project', 'project_no', value, this.model.id, callback)},
        ],
        distributionMethod: [
          { required: true, message: '请选择分配方式!' }
        ],
        estimatedContractAmount: [
          { required: false },
          // { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          { pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的金额!' }
        ],
        contactTel: [
          { required: false },
          { pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!' }
        ]
      },
      url: {
        add: '/api/erp/omc/project/erpOmcProjectApply/add',
        edit: '/api/erp/omc/project/erpOmcProjectApply/edit',
        queryById: '/api/erp/omc/project/erpOmcProjectApply/queryById',
        queryPrepareProjectById: '/api/erp/omc/prepareproject/erpOmcPrepareProject/queryById',
        queryProjectById: '/api/erp/omc/project/erpOmcProject/queryById',
        getProjectNo: '/api/erp/omc/project/erpOmcProjectApply/getProjectNo',
        generatedFormNumber: '/api/erp/base/generatedFormNumber'
      },
      customer_contacts: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 ',
      loading: false,
      dataSource: [],
      dictOptions: {},
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '业务分类编码',
          align: 'center',
          dataIndex: 'categoryCode',
          ellipsis: true,
          width: 180
        },
        {
          title: '业务分类名称',
          align: 'center',
          dataIndex: 'categoryName',
          ellipsis: true,
          width: 300
        },
        {
          title: '合同占比（%）',
          align: 'center',
          dataIndex: 'contractRate',
          ellipsis: true,
          width: 150
        },
        {
          title: '分配合同额（元）',
          align: 'center',
          dataIndex: 'contractAmount',
          ellipsis: true,
          width: 150
        },
        {
          title: '生产团队',
          align: 'center',
          dataIndex: 'productTeam',
          ellipsis: true,
          width: 300,
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['productTeam'], text + '')
            }
          }
        },
        {
          title: '团队负责人',
          align: 'center',
          dataIndex: 'teamLeader',
          ellipsis: true,
          width: 150,
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['teamLeader'], text + '')
            }
          }
        },
        {
          title: '任务说明',
          align: 'center',
          ellipsis: true,
          width: 200,
          dataIndex: 'taskDescription'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      // columns: [
      //   {
      //     title: '业务分类编码',
      //     align: 'center',
      //     key: 'categoryCode',
      //   },
      //   {
      //     title: '业务分类名称',
      //     align: 'center',
      //     key: 'categoryName',
      //   },
      //   {
      //     title: '合同占比',
      //     align: 'center',
      //     key: 'contractRate',
      //     type: JVXETypes.inputNumber,
      //   },
      //   {
      //     title: '分配合同额（元）',
      //     align: 'center',
      //     key: 'contractAmount',
      //     type: JVXETypes.inputNumber,
      //   },
      //   {
      //     title: '生产团队',
      //     align: 'center',
      //     key: 'productTeam_dictText',
      //   },
      //   {
      //     title: '团队负责人',
      //     align: 'center',
      //     key: 'teamLeader_dictText',
      //   },
      //   {
      //     title: '任务说明',
      //     align: 'center',
      //     key: 'taskDescription',
      //   }
      // ],
      detailColumns: [
        {
          title: '业务分类编码',
          align: 'center',
          dataIndex: 'categoryCode'
        },
        {
          title: '业务分类名称',
          align: 'center',
          dataIndex: 'categoryName'
        },
        {
          title: '合同占比（%）',
          align: 'center',
          dataIndex: 'contractRate'
        },
        {
          title: '分配合同额（元）',
          align: 'center',
          dataIndex: 'contractAmount'
        },
        {
          title: '生产团队',
          align: 'center',
          dataIndex: 'productTeam_dictText'
        },
        {
          title: '团队负责人',
          align: 'center',
          dataIndex: 'teamLeader_dictText'
        },
        {
          title: '任务说明',
          align: 'center',
          dataIndex: 'taskDescription'
        }
      ]
    }
  },
  watch: {
    model: {
				handler (val) {
					if (this.model.ownerUnit) {
            this.customer_contacts = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.ownerUnit + '\'';
          }
				},
				immediate: true
			}
  },
  computed: {
    proDisabled() {
      return true
    },
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          this.isDisableProjectNo = false
          return false
        }
        this.isDisableProjectNo = true
        return true
      }
      this.isDisableProjectNo = this.disabled
      return this.disabled
    },

    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    this.model.applyType = '2'
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData();
    // 加载数据字典信息
    this.initDictConfig();
    if (this.formDisabled) {
      this.columns.pop()
    }
    this.customKey = 'columns'
    this.columnswidth = this.columns.map(val => {
      return val.width
    })
  },
  methods: {
    // 是否存在收款合同
    async getContractByPro() {
      let res = await getAction(queryContractByProjectId, {
        projectId: this.model.projectId
      })

      if (res.success) {
        this.isHasContract = res.result == 1
      } else {
        this.$message.error(res.message || '查询是否存在收款合同失败！')
      }
    },
    ...mapGetters(['userInfo']),
    // 加载数据字典信息
    async initDictConfig() {
      initDictOptions('erp_omc_team_manager,alias_name,id').then(async (res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'productTeam', res.result)
        }
      })
      initDictOptions('erp_employee_file,name,id').then(async (res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'teamLeader', res.result)
        }
      })
    },
    add() {
      // this.model.ownerUnit = '';
      
      this.userName = this.userInfo().empName;// 申请人名称
      this.modelDefault.proposer = this.userInfo().empId; // 申请人
      this.modelDefault.proposerDeptId = this.userInfo().deptId; // 申请部门
      this.modelDefault.createTime = moment().format('YYYY-MM-DD HH:mm');
      this.modelDefault.isChangeName = '0'; // 是否变更醒目名称默认为否
      this.isHasContract = false
      projectId = ''
      this.edit(this.modelDefault);
      // this.generatedFormNumber();
    },
    async edit(record) {
      await this.$refs['form'].clearValidate();
      this.dataSource = await []
      this.isDisableProjectNo = true
      await this.$refs.form.resetFields();
      this.model = await Object.assign({}, record);
      projectId = this.model.projectId
      this.model.lx = 2;
      this.model.applyType = '2'
      this.oldProjectName = record.projectId_dictText
      this.inputChangeName(this.model.isChangeName)
      if (this.model.id) {
        this.customer_contacts = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0'
        if (this.model.projectId) {
          this.getContractByPro()
        }
      }
      if (this.model.estimatedContractAmount) {
        this.$set(this.model, 'estimatedContractcapitalChineseAmount', convertCurrency(this.model.estimatedContractAmount))
      }
      getAction('/api/erp/omc/project/erpOmcProjectTask/getResultlistById', { id: this.model.id == null ? '1' : this.model.id }).then(async (res) => {
        if (res.result) {
          this.dataSource = res.result
        } else {
          this.dataSource = []
        }
      });
      this.visible = true
      this[this.customKey].forEach((val, index) => {
        val.width = this[this.customKey + 'width'][index]
      })
    },

    // 选择变更项目名称
    inputChangeName (val) {
      if (val == 1) {
        this.$set(this.validatorRules, 'projectName', [{ required: true, message: '请输入项目名称!' }, { validator: checkProjectName, trigger: 'blur' }])
      } else {
        this.$set(this.model, 'projectName', this.oldProjectName)
        this.$delete(this.validatorRules, 'projectName')
      }
    },
    // 修改项目名称修改流程标题
    changeTitle() {
      this.$set(this.model, 'bpmBizTitle', this.model.projectName)
    },
    // 业务分类新增、编辑
    addOrEdit(record) {
      if (!this.model.distributionMethod) {
        return this.$message.info('请选择分配方式！')
      }
      if (parseInt(this.model.estimatedContractAmount) !== 0) {
        if (!this.model.estimatedContractAmount) {
          return this.$message.info('请输入预计合同额！')
        }
      }

      if (record) {
        this.$refs.categoryList.title = '修改'
        this.$refs.categoryList.edit(record)
      } else {
        this.$refs.categoryList.add()
        this.$refs.categoryList.title = '新增'
      }

      this.$refs.categoryList.assignedAmount = this.model.estimatedContractAmount
      this.$refs.categoryList.disableSubmit = false
    },
    // 业务分类删除
    handleDelete(id) {
      for (let i = 0; i < this.dataSource.length; i++) {
        if (this.dataSource[i].id == id) {
          this.dataSource.splice(i, 1);
        }
      }
    },
    // modalFormOk(data) {
    //   this.loading = true;
    //   let flag = true;
    //   for (let i = 0; i < this.dataSource.length; i++) {
    //     if (this.dataSource[i].id == data.id) {
    //       this.dataSource.splice(i, 1, data);
    //       flag = false;
    //     }
    //   }
    //   if (flag) {
    //     this.dataSource.push(data);
    //   }
    //   this.loading = false;
    // },
    modalFormOk(data) {
      this.loading = true;
      let flag = true;
      // if(!this.dataSource){
      //  this.dataSource=[];
      // }
      for (let i = 0; i < this.dataSource.length; i++) {
        if (this.dataSource[i].id == data.id) {
          this.dataSource.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.dataSource.push(data);
      }
      this.loading = false;
      // //没有id相等的则返回false
      // let flag = true;
      // 第一次新增
      // if (this.dataSource == null) {
      //     this.dataSource = []
      //     this.dataSource.push(data);
      // }else{
      //   for (let i = 0; i < this.dataSource.length; i++) {
      //     if (this.dataSource[i].id == data.id) {
      //         let a = this.dataSource.splice(i, 1, data);
      //     }
      //   }
        // //后续插入
        // let flagA = false;
        // for (let i = 0; i < this.dataSource.length; i++) {
        //     if (this.dataSource[i].id != data.id) {
        //         flagA = true
        //     }
        // }
        // if(flagA){
        //   this.dataSource.push(data);
        // }
      },

        // else{
        //   //id相等则为编辑
        //    for (let i = 0; i < this.dataSource.length; i++) {
        //     if (this.dataSource[i].id == data.id) {
        //         this.dataSource.splice(i, 1, data);
        //     }
        //   }
        // }
    //     if(flag){

    //     }
    //   // if (flag) {
    //   // }
    //   this.loading = false;
    // },
    getProjectNo() {
      if (this.model.isPrepareEstablish == '0') {
        getAction(this.url.getProjectNo, {}).then((res) => {
          if (res.success) {
            let data = res.result.records || res.result
            this.$set(this.model, 'projectNo', data)
          }
        })
      }
    },
    convertMoney() {
      let money = this.model.estimatedContractAmount
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', convertCurrency(money))

      this.getForMoney()
    },
    getForMoney() {
      if (this.dataSource.length > 0) {
        this.dataSource.forEach(item => {
          if (parseInt(this.model.estimatedContractAmount) === 0) {
            item.contractAmount = 0
            item.contractRate = 0
          } else {
            if (!this.model.estimatedContractAmount) {
              return
            }

            if (this.model.distributionMethod == '1') {
              // 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
              if (item.contractRate) {
                let amount = this.model.estimatedContractAmount * item.contractRate / 100
                item.contractAmount = Math.round((amount + Number.EPSILON) * 100) / 100

                // item.contractAmount = parseFloat(item.contractRate*0.01*parseFloat(this.model.estimatedContractAmount)).toFixed(2)
              }
          } else if (this.model.distributionMethod == '2') {
            // 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
            if (item.contractAmount) {
              let rate = item.contractAmount / this.model.estimatedContractAmount * 100
              item.contractRate = Math.round((rate + Number.EPSILON) * 100) / 100
                // item.contractRate = parseFloat(parseFloat(item.contractAmount) / parseFloat(this.model.estimatedContractAmount)*100).toFixed(2)
              }
            }
          }
        })
      }
    },
    handleValueChange(event) {
      const { rowIndex, columnIndex, value } = event
      if (this.model.estimatedContractAmount) {
        if (columnIndex == 3) {
          let amount = this.model.estimatedContractAmount * value / 100
          this.dataSource[rowIndex].contractAmount = Math.round((amount + Number.EPSILON) * 100) / 100;
        } else if (columnIndex == 4) {
          let rate = value / this.model.estimatedContractAmount * 100
          this.dataSource[rowIndex].contractRate = Math.round((rate + Number.EPSILON) * 100) / 100;
        }
      }
    },
    contactsChange(val) {
      getAction('/api/erp/omc/customermanager/erpOmcCustomerManagerContact/queryById', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          // this.model.lxdh = data.lxfs;
          this.$set(this.model, 'contacts', val)
          this.$set(this.model, 'contactTel', data.lxfs)
        }
      })
    },
    ownerUnitChange() {
      this.$set(this.model, 'contacts', null)
      this.$set(this.model, 'contactTel', null)
      this.customer_contacts = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.ownerUnit + '\'';
    },
    projectChange(project) {
      this.$set(this.model, 'finalProjectId', project[0].id)
      this.$set(this.model, 'projectId', project[0].id)
      projectId = project[0].id
      this.$set(this.model, 'bpmBizTitle', project[0].projectName)// 标题
      this.$set(this.model, 'isPrepareEstablish', project[0].isPrepareEstablish)
      this.$set(this.model, 'projectName', project[0].projectName)
      this.oldProjectName = project[0].projectName
      this.$set(this.model, 'projectType', project[0].projectType)
      this.$set(this.model, 'teamName', project[0].oldTeamId?project[0].oldTeamId:project[0].teamName)
      this.$set(this.model, 'undertaker', project[0].undertaker)
      this.$set(this.model, 'isBidding', project[0].isBidding)
      this.$set(this.model, 'isEnvironmentalAssessmentProject', project[0].isEnvironmentalAssessmentProject)
      this.$set(this.model, 'signUnit', project[0].signUnit)
      this.$set(this.model, 'year', project[0].year)
      this.$set(this.model, 'ownerUnit', project[0].ownerUnit)
      this.$set(this.model, 'contacts', project[0].contacts)
      this.$set(this.model, 'contactTel', project[0].contactTel)
      this.$set(this.model, 'areaCode', project[0].areaCode)
      this.$set(this.model, 'projectAddress', project[0].projectAddress)
      this.$set(this.model, 'projectSource', project[0].projectSource)
      this.$set(this.model, 'distributionMethod', project[0].distributionMethod)
      this.$set(this.model, 'estimatedContractAmount', project[0].estimatedContractAmount)
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', project[0].estimatedContractcapitalChineseAmount)
      this.$set(this.model, 'establishReason', project[0].establishReason)
      this.$set(this.model, 'attachment', project[0].attachment)
      this.$set(this.model, 'applyType', '2')
      this.$set(this.model, 'lx', '2')
      this.$set(this.model, 'projectNo', project[0].projectNo)
      this.$set(this.model, 'projectEstablishDate', project[0].projectEstablishDate)// 立项日期
      if (this.model.projectId) {
        this.getContractByPro()
      }
      // 根据项目id 查看业务分类
      this.dataSource = []
      getAction('/api/erp/omc/project/erpOmcProjectTask/queryByProjectId', { projectId: this.model.projectId }).then((res) => {
        if (res.success) {
          this.dataSource = res.result;
        }
      });
    },
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'LX', subSystemCode: '05' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'projectNo', res.result)
        }
      })
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.detailFlag = true;
            this.edit(res.result);
          }
        });
      }
    },

    validateForm() {
      var that = this
      this.$emit('unButtonDisable');
      return this.$refs.form.validate().then(async () => {
        if (this.dataSource == null || this.dataSource.length <= 0) {
          this.$message.warning('必须填写业务分类信息！');
          return Promise.reject('必须填写业务分类信息！')
        }

        if (this.model.distributionMethod == '1') {
          let rate = 0
          this.dataSource.forEach(val => {
            rate += parseFloat(val.contractRate)
          })
          if (rate != 100 && parseInt(this.model.estimatedContractAmount) !== 0) {
            this.$message.warning('合同占比相加不等于100%，请重新填写')
            return Promise.reject('合同占比相加不等于100%，请重新填写')
          }
        } else if (this.model.distributionMethod == '2') {
          let total = 0
          this.dataSource.forEach(val => {
            total += parseFloat(val.contractAmount)
          })
          if (total.toFixed(2) != parseFloat(that.model.estimatedContractAmount).toFixed(2)) {
            this.$message.warning('所有分配金额总计和预计合同额不相等，请重新填写')
            return Promise.reject('所有分配金额总计和预计合同额不相等，请重新填写')
          }
        }

        // var isJudge = -1
        // for (var i = 0; i < this.dataSource.length; i++) {
				// 	var isTrue = await getAction('/api/erp/omc/project/erpOmcProjectApply/valdateProductTeamLeader', { teamId: this.dataSource[i].productTeam }).then((res) => {
				// 		if (res.success) {
				// 			return res.success
				// 		} else {
        //       isJudge = i
				// 			var info = filterMultiDictText(this.dictOptions['productTeam'], this.dataSource[i].productTeam + '') + '团队，生产负责人岗位未找到'
        //       this.$message.warning(info);
				// 			return res.success
				// 		}
				// 	})
        //   if (!isTrue) {
        //     break
        //   }
				// }
        // if (isJudge != -1) {
        //   return Promise.reject('生产负责人岗位未找到')
        // }
      })
    },

    async submitForm(type) {
      const that = this;
      if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
        // 触发表单验证
        await this.validateForm()

        let teamIdArr = []
        for (let it of this.dataSource) {
          let params = {
            teamId: it.productTeam,
            productTeam: filterMultiDictText(this.dictOptions['productTeam'], it.productTeam + '')
          }
          teamIdArr.push(params)
        }
      let rr = await postAction(valdateProductTeamLeader, teamIdArr)
      if (!rr.success) {
        return this.$message.error(rr.message)
      }
        that.submit(type)
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
    },
    submit (type) {
      const that = this;
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }
      this.model.categoryList = this.dataSource || [];
      httpAction(httpurl, this.model, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          if (method == 'post') {
            that.model.id = res.result;
          }
          that.$emit('ok', type, that.model);
        } else {
          that.$message.warning(res.message);
          that.$emit('unButtonDisable');
        }
      }).catch((error) => {
        that.$emit('unButtonDisable', error);
      }).finally(() => {
        that.confirmLoading = false;
      })
    },
    // async submitForm() {
    //   const that = this;
    //   // 触发表单验证
    //   await this.validateForm()

    //   let teamIdArr = []
    //   for (let it of this.dataSource) {
    //     let params = {
    //       teamId: it.productTeam,
    //       productTeam: filterMultiDictText(this.dictOptions['productTeam'], it.productTeam + '')
    //     }
    //     teamIdArr.push(params)
    //   }

    //   // // 去重
    //   // var newArr = teamIdArr.filter(function(item,index){
    //   //   return teamIdArr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个
    //   // });

    //   let rr = await postAction(valdateProductTeamLeader,teamIdArr)
    //   if(!rr.success){
    //     return this.$message.error(rr.message)
    //   }

    //   that.confirmLoading = true;
    //   let httpurl = '';
    //   let method = '';
    //   if (!this.model.id) {
    //     httpurl += this.url.add;
    //     method = 'post';
    //   } else {
    //     httpurl += this.url.edit;
    //     method = 'put';
    //   }
    //   let dataSource = this.dataSource;
    //   this.model.categoryList = dataSource
    //   httpAction(httpurl, this.model, method).then((res) => {
    //     if (res.success) {
    //       that.$message.success(res.message);
    //       that.$emit('ok');
    //     } else {
    //       that.$message.warning(res.message);
    //     }
    //   }).finally(() => {
    //     that.confirmLoading = false;
    //   })
    // },

    // 点击打印
    onPrint () {
      let print = new Print({
        el: '#projectApplyChangeContent',
        popTitle: '立项申请明细 · 禾美环保',
        endCallback() {

        }
      })
    }
  }
}
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
